package org.example.gui.panel;

import org.example.dao.CategoryDAO;
import org.example.entity.Category;
import org.example.gui.listener.CategoryListener;
import org.example.gui.model.CategoryTableModel;
import org.example.util.ColorUtil;
import org.example.util.GUIUtil;

import javax.swing.*;
import java.awt.*;

/**
 * 界面类 CategoryPanel 分类页
 */

public class CategoryPanel extends WorkingPanel {
    public static CategoryPanel instance = new CategoryPanel();

    public JButton bAdd = new JButton("新增");
    public JButton bEdit = new JButton("编辑");
    public JButton bDelete = new JButton("删除");

    private final CategoryTableModel categoryTableModel = new CategoryTableModel();
    private final JTable table = new JTable(categoryTableModel);


    public CategoryPanel() {
        GUIUtil.setColor(ColorUtil.blueColor, bAdd, bEdit, bDelete);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane sp = new JScrollPane(table);
        JPanel pSubmit = new JPanel();
        pSubmit.add(bAdd);
        pSubmit.add(bEdit);
        pSubmit.add(bDelete);

        this.setLayout(new BorderLayout());
        this.add(sp, BorderLayout.CENTER);
        this.add(pSubmit, BorderLayout.SOUTH);

        this.addListener();
    }



    public Category getSelectedCategory() {
        int index = table.getSelectedRow();
        return categoryTableModel.categoryList.get(Math.max(index, 0));
    }


    public void updateData() {
        categoryTableModel.categoryList = CategoryDAO.listAllCategory();
        table.updateUI();
        if (0 == categoryTableModel.categoryList.size()) {
            bEdit.setEnabled(false);
            bDelete.setEnabled(false);
        } else {
            bEdit.setEnabled(true);
            bDelete.setEnabled(true);
        }
    }


    public void addListener() {
        CategoryListener categoryListener = new CategoryListener();
        bDelete.addActionListener(categoryListener);
        bEdit.addActionListener(categoryListener);
        bAdd.addActionListener(categoryListener);
    }
}